package com.zuxia.struts2.inter.util;

import com.zuxia.struts2.base.exception.MyException;
import com.zuxia.struts2.inter.bean.FileInfo;
import org.apache.commons.io.FileUtils;

import java.io.File;

/**
 * 判断int类型的值是否为空
 */
public class ServiceUtil {
    public static int checkNull(int obj, String errorMsg) throws MyException {
        if (obj == 0) {
            throw new MyException(errorMsg);
        }
        return obj;
    }

    /**
     * 判断String类型的值是否为空
     *
     * @param obj
     * @param errorMsg
     * @return
     * @throws MyException
     */
    public static String checkNull(String obj, String errorMsg) throws MyException {
        if (obj == null || "".equals(obj)) {
            throw new MyException(errorMsg);
        }
        return obj;
    }


    /**
     * 判断obj值是否为空
     *
     * @param obj
     * @param errorMsg
     * @return
     * @throws MyException
     */
    public static Object checkNull(Object obj, String errorMsg) throws MyException {
        if (obj == null) {
            throw new MyException(errorMsg);
        }
        return obj;
    }


    /**
     * 判断上传的文件格式是否为图片格式
     *
     * @param fileType
     * @return
     * @throws MyException
     */
    public static void checkImg(String fileType) throws MyException {
        if ("image/gif".equals(fileType) ||
                "image/jpg".equals(fileType) ||
                "image/jpeg".equals(fileType) ||
                "image/png".equals(fileType)) {//判断图片格式是否正确
        } else {
            throw new MyException("图片格式不正确");
        }
    }

    /**
     * 保存图片到服务器上的方法
     * @param url
     * @param fileInfo
     * @throws MyException
     */
    public static void savePicToServer(String url, FileInfo fileInfo) throws MyException {
        try {
            //上传图片到本地方法
            File File = new File(url, fileInfo.getFileFileName());
            FileUtils.copyFile(fileInfo.getFile(), File);
        } catch (Exception e) {
            throw new MyException("添加图片到["+url+"]失败");
        }
    }

    /**
     * 加密字符的方法（宇宙限量版）
     * @param uuid
     */

    public  static  String strToCode(String str,String uuid) throws MyException {
        SHAencryption sha=new SHAencryption();
        if (str==""||"".equals(str)){
            throw new MyException("需要加密的密码不能为空");
        }
        String codeStr="";
        try {
            String str1=sha.encryptSHA(str);
            String str2=sha.encryptSHA(str1+uuid);
            codeStr = sha.encryptSHA(str2);

        } catch (Exception e) {
            throw new MyException("密码加密失败");
        }
        return codeStr;
    }


}
